package com.dtsz.m2.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.dtsz.m2.BuildConfig;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.ui.model.CertificationVo;
import com.dtsz.m2.ui.view.CBProgressBar;
import com.dtsz.m2.utils.FileUploadUtils;
import com.dtsz.m2.utils.FileUtil;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.volley.state.HUCState;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class IdentificationActivity extends BaseActivity {
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    //头像2
    private ImageView headImage2;
    //调用照相机返回图片文件
    private File tempFile;

    private AlertDialog cerDialog;

    private ImageView ivFm, ivZm;
    //记录照片上传地址
    private int isFlag;
    private CBProgressBar progressBar;

    private EditText etName, etCard;

    private Button btUpload, btLogin;
    private TextView btSate;

    private CertificationVo certificationVo = new CertificationVo();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_identification);
        super.onCreate(savedInstanceState);
        tvActionbarTitle.setText("实名认证");
        String name = getIntent().getExtras().getString("name");
        etName.setText(name);
        getCertification();
    }


    @Override
    public void initView() {
        super.initView();
        ivFm = findViewById(R.id.im_fm);
        ivZm = findViewById(R.id.im_zm);
        etName = findViewById(R.id.et_name);
        etCard = findViewById(R.id.et_card);
        btUpload = findViewById(R.id.bt_upload);
        btLogin = findViewById(R.id.bt_login);
        btSate = findViewById(R.id.tv_state);
    }

    @Override
    public void initClick() {
        super.initClick();
        ivFm.setOnClickListener(this);
        ivZm.setOnClickListener(this);
        btUpload.setOnClickListener(this);
        findViewById(R.id.ll_click_ck).setOnClickListener(this);
        btLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_actionbar_left:
                if ("2".equals(certificationVo.getBcState())) {
                    getDataName();
                } else {
                    finish();
                }
                break;
            case R.id.im_zm:
                isFlag = 1;
                uploadHeadImage();
                break;
            case R.id.im_fm:
                isFlag = 2;
                uploadHeadImage();
                break;
            case R.id.bt_upload:
                //sendIntent(this, VideoActivity.class, HUCState.HUC_REQEUST_CODE_10);
                isFlag = 3;
                //权限判断
                if (ContextCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(IdentificationActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到相册
                    getVideo();
                }
                break;
            case R.id.ll_click_ck:
                String url = certificationVo.getBcVideo();
                if (!StringUtils.isEmpty(url)) {
                    Intent it = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.parse(url);
                    it.setDataAndType(uri, "video/mp4");
                    startActivity(it);
                } else {
                    showToast("请点击上传视频");
                }
                break;
            case R.id.bt_login:
                uploadInfo();
                break;
        }
    }

    private void uploadInfo() {
        String card = etCard.getText().toString();
        if (!StringUtils.isIDNumber(card)) {
            showToast("身份证格式错误");
            return;
        } else {
            certificationVo.setBcCard(card);
        }
        String zmImage = certificationVo.getBcZmImage();
        String fmImage = certificationVo.getBcFmImage();
        if (StringUtils.isEmpty(zmImage) || "无".equals(zmImage)) {
            showToast("请上传身份证头像面");
            return;
        }
        if (StringUtils.isEmpty(fmImage) || "无".equals(fmImage)) {
            showToast("请上传身份证国徽面");
            return;
        }
        String video = certificationVo.getBcVideo();
        if (StringUtils.isEmpty(video) || "无".equals(video)) {
            showToast("请上传手持身份证视频");
            return;
        }
        certificationVo.setToken(pageVo.getToken());
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.CERTIFICATION_URL,
                hucParameInterfase.getRequestParameter(certificationVo), true);

    }

    private void getCertification() {
        hucRequestInterfase.executeStr(this, CertificationVo.class,
                HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.GETCERTIFICATION_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            System.out.println("按下了back键   onKeyDown()");
            if ("2".equals(certificationVo.getBcState())) {
                getDataName();
            } else {
                finish();
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void getDataName() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        dialog.setMessage("退出此页面后，本次实名认证名额将会转移给其他人");
        dialog.setPositiveButton("确定", null);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cerDialog.dismiss();
            }
        });

        cerDialog = dialog.create();
        cerDialog.setCancelable(false);
        cerDialog.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        cerDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户
                        hucRequestInterfase.executeStr(IdentificationActivity.this, CertificationVo.class,
                                HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.DELETECERTIFICATION_URL,
                                hucParameInterfase.getRequestParameter(pageVo), true);
                    }
                });
    }

    /**
     * 上传头像
     */
    private void uploadHeadImage() {
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_image, null);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_identification, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });

//        btnCarema.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) ||
//                        !(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) ||
//                        !(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) ||
//                        !(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
//                    //没有权限，申请权限
//                    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE};
//                    //申请权限，其中RC_PERMISSION是权限申请码，用来标志权限申请的
//                    ActivityCompat.requestPermissions(IdentificationActivity.this, permissions, WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
//
//                } else {
//                    //跳转到调用系统相机
//                    gotoCamera();
//                }
//                popupWindow.dismiss();
//            }
//        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                if (ContextCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(IdentificationActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到相册
                    gotoPhoto();

                }
                popupWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }


    /**
     * 外部存储权限申请返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults.length == 4
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED
                    && grantResults[3] == PackageManager.PERMISSION_GRANTED) {
                gotoCamera();
            }
        } else if (requestCode == READ_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                switch (isFlag) {
                    case 1:
                    case 2:
                        gotoPhoto();
                        break;
                    default:
                        getVideo();
                        break;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    uploadImageLoad(false);
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = intent.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    assert cursor != null;
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    tempFile = new File(picturePath);
                    uploadImageLoad(false);
                }
                break;
            case HUCState.HUC_REQEUST_CODE_10:
                if (intent != null) {
                    Bundle bundle = intent.getExtras();
                    String url = bundle.getString("URL");
                    if (!StringUtils.isEmpty(url)) {
                        certificationVo.setBcVideo(url);
                    }
                }
            case HUCState.HUC_REQEUST_CODE_5:
                if (intent != null) {
                    Uri selectedImage = intent.getData();
                    try {
                        String str = getPathrimay(IdentificationActivity.this, selectedImage);
                        tempFile = new File(str);
                        uploadImageLoad(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // uploadImageLoad();
                break;
        }
    }

    /**
     * 跳转到相册
     */
    private void gotoPhoto() {
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    private void getVideo() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        // photoPickerIntent.setType("image/*");
        //intent.setType(“image/*”);
        //下面三个如果在 ACTION_PICK 下没效，就用ACTION_GET_CONTENT,这个会提示你用那个软件打开
        //intent.setType(“audio/*”); //选择音频
        photoPickerIntent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
        startActivityForResult(Intent.createChooser(photoPickerIntent, "请选择视频"), HUCState.HUC_REQEUST_CODE_5);
    }

    /**
     * 跳转到照相机
     */
    private void gotoCamera() {
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳系统相机转到调用
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(IdentificationActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }


    ////////////////////////////////////////////////////////////////////

    /**
     * 上传头像
     */
    PopupWindow popupWindow = null;

    private void uploadImageLoad(boolean flag) {
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_upload, null);
        progressBar = view.findViewById(R.id.my_progress);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_identification, null);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });
        if (flag) {
            new Thread(networkTask).start();
        } else {
            new Thread(networkTaskImage).start();
        }

    }

    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {
        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            try {
                Map<String, String> map = new HashMap<String, String>();
                map.put("token", pageVo.getToken());
                FileUploadUtils.post(IdentificationActivity.this, HUCState.HUC_REQEUST_CODE_2, UrlConfig.FILEUPLOAD_URL, map, tempFile, handler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    Runnable networkTaskImage = new Runnable() {
        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            try {
                Map<String, String> map = new HashMap<String, String>();
                map.put("token", pageVo.getToken());
                FileUploadUtils.post(IdentificationActivity.this, HUCState.HUC_REQEUST_CODE_2, UrlConfig.ECOLOGYIMAGE_URL, map, tempFile, handler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_2:
                try {
                    JSONObject jsonObject = new JSONObject((String) response);
                    String code = jsonObject.getString("code");
                    String url = jsonObject.getString("datalist");
                    Message msg = handler.obtainMessage();
                    msg.what = HUCState.HUC_REQEUST_CODE_2;
                    msg.obj = url;
                    msg.sendToTarget();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                String msg = (String) response;
                showToast(msg);
                if ("提交成功".equals(msg)) {
                    finish();
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_4:
                if (response instanceof CertificationVo) {
                    CertificationVo certificationVo = (CertificationVo) response;
                    this.certificationVo = certificationVo;
                    pageVo.setId(certificationVo.getId());
                    String state = certificationVo.getBcState();
                    if ("0".equals(state)) {//审核中
                        btLogin.setText("审核中");
                        isIdent();
                    } else if ("-1".equals(state)) {//审核失败
                        isIdentif(certificationVo.getBcDescription());
                    }
                    etCard.setText(certificationVo.getBcCard());
                    Glide.with(IdentificationActivity.this).load(certificationVo.getBcZmImage()).into(ivZm);
                    Glide.with(IdentificationActivity.this).load(certificationVo.getBcFmImage()).into(ivFm);
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_5:
                finish();
                break;

        }
    }

    AlertDialog alertDialog1;

    private void isIdent() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        //dialog.setTitle("");
        dialog.setMessage("正在审核中");
        dialog.setPositiveButton("返回", null);

        alertDialog1 = dialog.create();
        alertDialog1.setCancelable(false);
        alertDialog1.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户v
                        finish();
                    }
                });
    }

    private void isIdentif(String content) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("审核失败原因");
        dialog.setMessage(content);
        dialog.setPositiveButton("确定", null);

        alertDialog1 = dialog.create();
        alertDialog1.setCancelable(false);
        alertDialog1.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户v
                        alertDialog1.dismiss();
                    }
                });
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HUCState.HUC_REQEUST_CODE_1:
                    progressBar.setProgress(msg.arg1);
                    if (msg.arg1 == 100) {
                        popupWindow.dismiss();
                    }
                    break;
                case HUCState.HUC_REQEUST_CODE_2:
                    String url = (String) msg.obj;
                    if (isFlag == 1) {//正面广告
                        certificationVo.setBcZmImage(url);
                        Glide.with(IdentificationActivity.this).load(url).into(ivZm);

                    } else if (isFlag == 2) {//反面
                        certificationVo.setBcFmImage(url);
                        Glide.with(IdentificationActivity.this).load(url).into(ivFm);
                    } else {
                        btSate.setVisibility(View.VISIBLE);
                        //显示成功按钮
                        certificationVo.setBcVideo(url);
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };


    /**
     * 获取视频第一帧图片
     */
    private Bitmap createVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        return bitmap;
    }

    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     */
    public String getPathrimay(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


}
